package com.gitee.qdbp.general.system.web.views;

import java.util.List;
import java.util.Properties;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.servlet.ModelAndView;
import com.gitee.qdbp.able.beans.DepthMap;
import com.gitee.qdbp.base.utils.SessionTools;
import com.gitee.qdbp.general.system.api.permission.model.ResourceCascadeBean;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * 管理平台页面跳转基础处理
 *
 * @author zhaohuihua
 * @version 170427
 */
public class EasyuiViewsTools extends SimpleViewsTools {

    protected String homePage = "pc/_/$index";
    protected String launchPage = "pc/_/$launch";

    public EasyuiViewsTools(Properties setting) {
        super(setting);
    }

    public ModelAndView toEasyuiModuleHome(boolean tabs, String module) {
        SecurityUtils.getSubject().isPermitted("*");

        DepthMap dpm = getEasyuiBasePageVariables(tabs, module);
        String pagePath = homePage;
        dpm.put("indent", tabs ? "#" : ".");
        return new ModelAndView(pagePath, "pv", dpm.map());
    }

    public ModelAndView toEasyuiModulePage(boolean tabs, String module, String channel, String group, String page) {
        SecurityUtils.getSubject().isPermitted("*");

        DepthMap dpm = getEasyuiBasePageVariables(tabs, module);
        String pagePath = "pc/" + channel + "/" + group + "/" + page;
        dpm.put("page", "/WEB-INF/pc/" + pagePath + ".jsp");
        dpm.put("view", pagePath);
        dpm.put("indent", tabs ? "#" : "../../..");
        String view = tabs ? pagePath : launchPage;
        return new ModelAndView(view, "pv", dpm.map());
    }

    public DepthMap getEasyuiBasePageVariables(boolean tabs, String module) {
        String uri = "/" + module + "/";
        List<ResourceCascadeBean> menus = getMenus(module);
        DepthMap dpm = getPageVariables();
        dpm.put("tabs", tabs);
        dpm.put("module", uri);
        dpm.put("menus", menus);
        return dpm;
    }

    public List<ResourceCascadeBean> getMenus(String module) {
        if (VerifyTools.isBlank(module) || "test".equals(module)) {
            return null;
        }

        ResourceCascadeBean root = (ResourceCascadeBean) SessionTools.getUserResources();
        if (root == null) {
            return null;
        }

        String modulePath = "/" + module + "/";
        List<ResourceCascadeBean> modules = root.getChildren();
        if (modules == null) {
            return null;
        }
        for (ResourceCascadeBean m : modules) {
            if (modulePath.equals(m.getUrl())) {
                return m.getChildren();
            }
        }
        return null;
    }

}
